//
//  SGWindowController.m
//  iPing
//
//  Created by Thomas on 8/11/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "SGWindowController.h"
#import "StoryControllerView.h"
#import "TCSGToolbarLibrary.h"


@implementation SGWindowController
- (void)setManagedObjectContext:(NSManagedObjectContext *)moc
{
	[moc retain];
	[managedObjectContext release];
	managedObjectContext = moc;
}
- (void)dealloc
{
	[managedObjectContext release];
	[super dealloc];
}
- initWithPath:(NSString *)newPath
{
	NSLog(@"1");
	return [super initWithWindowNibName:@"StoryGrabberWindow"];
}
- (IBAction)setSearchCategoryFrom:(NSMenuItem *)menuItem
{

	[myCurrentViewController setsearchCategory:[menuItem tag]];
	//NSLog(@"tag: %i",searchCategory);
    [[searchFields cell] setPlaceholderString:[menuItem title]];
}

- (IBAction)search:(id)sender
{
	[myCurrentViewController searchWithString:[searchFields stringValue]];
}
- (void)changeViewController:(NSInteger)whichViewTag
{
	// we are about to change the current view controller,
	// this prepares our title's value binding to change with it
	[self willChangeValueForKey:@"viewController"];
	
	if ([myCurrentViewController view] != nil)
		[[myCurrentViewController view] removeFromSuperview];	// remove the current view
	
	if (myCurrentViewController != nil)
		[myCurrentViewController release];		// remove the current view controller
	
	switch (whichViewTag)
	{
		case 0:	// swap in the "CustomImageViewController - NSImageView"
		{
			[[self window] setTitle:@"Grabber"];
			StoryControllerView* imageViewController =[[StoryControllerView alloc] initWithNibName:@"StoryGrabber" bundle:nil];
						
			if (imageViewController != nil)
			{
				
				myCurrentViewController = imageViewController;	// keep track of the current view controller
				[myCurrentViewController setTitle:@"StoryGrabber"];
				[myCurrentViewController setManagedObjectContext:managedObjectContext];
				NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"GrabberToolbar"];
				[toolbar setDelegate:self];
				[toolbar setAllowsUserCustomization:YES];
				[toolbar setAutosavesConfiguration:YES];
				[self.window setToolbar:toolbar];
			}
			break;

		}
			
		case 1:	// swap in the "CustomTableViewController - NSTableView"
		{
			StoryLibraryView* tableViewController =
			[[StoryLibraryView alloc] initWithNibName:@"Library" bundle:nil];
			[[self window] setTitle:@"Library"];
			if (tableViewController != nil)
			{
				NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"LibraryToolbar"];
				
				myCurrentViewController = tableViewController;	// keep track of the current view controller
				[myCurrentViewController setTitle:@"Library"];
				[myCurrentViewController setManagedObjectContext:managedObjectContext];
				//[self.window setToolbar:toolbar];

					[toolbar setDelegate:self];
					[toolbar setAllowsUserCustomization:YES];
					[toolbar setAutosavesConfiguration:YES];
				[self.window setToolbar:toolbar];
				//[myCurrentViewController setAddedObjects:addedObjects];
				addedObjects = nil;
			}
			
			break;
		}
		case 2:
		{
			[[self window] setTitle:@"Browser"];
			StoryBrowserView * tableViewController = [[StoryBrowserView alloc] initWithNibName:@"StoryBrowserView" bundle:nil];
			NSString *HTMLCode = [myCurrentViewController getHTMLCode];
			if (tableViewController != nil)
			{
				myCurrentViewController = tableViewController;
				
				//Create Custom Toolbar for The Browser
				
				NSToolbar *toolbar = [[NSToolbar alloc] initWithIdentifier:@"BrowserToolbar"];
				
				[myCurrentViewController setTitle:@"Browser"];
				[myCurrentViewController setManagedObjectContext:managedObjectContext];
				[myCurrentViewController setStoryHTMLCode:HTMLCode];
				
				//[self.window setToolbar:toolbar];
				
				[toolbar setDelegate:self];
				[toolbar setAllowsUserCustomization:YES];
				[toolbar setAutosavesConfiguration:NO];
				NSLog(@"%@",[toolbar toolbarDefaultItemIdentifiers:toolbar]);
				[self.window setToolbar:toolbar];
				//[myCurrentViewController setAddedObjects:addedObjects];
				addedObjects = nil;
			}
		}
	}
	NSWindow *w = [self window];
	
	NSView *v = [myCurrentViewController view];
	
	NSSize currentSize = [myTargetView frame].size;
	
	NSSize newSize = [v frame].size;
	
	float deltaWidth = newSize.width - currentSize.width;
	float deltaHeight = newSize.height - currentSize.height;
	
	NSRect windowFrame = [w frame];
	windowFrame.size.height += deltaHeight;
	windowFrame.origin.y -= deltaHeight;
	windowFrame.size.width += deltaWidth;
	
	//[myTargetView setContentView:nil];
	[w setFrame:windowFrame
		display:YES
		animate:YES];
	
	// embed the current view to our host view
	[myTargetView addSubview: [myCurrentViewController view]];
	
	// make sure we automatically resize the controller's view to the current window size
	[[myCurrentViewController view] setFrame: [myTargetView bounds]];
	
	// set the view controller's represented object to the number of subviews in that controller
	// (our NSTextField's value binding will reflect this value)
	[myCurrentViewController setRepresentedObject: [NSNumber numberWithUnsignedInt: [[[myCurrentViewController view] subviews] count]]];
	
	//[self didChangeValueForKey:@"viewController"];	// this will trigger the NSTextField's value binding to change
}
-(IBAction)selectView:(id)pId;
{
	[self changeViewController:[pId tag]];
}

- (void)awakeFromNib
{
	
	DeviceDict = [[NSMutableDictionary alloc] init];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setObjects:) name:@"Add to Controller" object:nil];
	[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(setPopUpSelection:) name:@"BrowserChapter" object:nil];
	[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(mountedDisk:) name:NSWorkspaceDidMountNotification object:nil];
	[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver:self selector:@selector(unmountedDisk:) name:NSWorkspaceDidUnmountNotification object:nil];
	[self changeViewController: 1];
}
-(void)unmountedDisk:(NSNotification *)note
{
	NSLog(@"unmounting");
	if([[[note userInfo] objectForKey:@"NSDevicePath"] isEqualToString:PRS505Device])
	{
		PRS505Device = nil;
	}
	if([[[note userInfo] objectForKey:@"NSDevicePath"] isEqualToString:PRS505Media])
	{
		PRS505Media = nil;
	}
	NSLog(@"PRS505Device: %@, Media: %@",PRS505Device, PRS505Media);

	
}
-(void)mountedDisk:(NSNotification *)note
{
    NSDictionary *pathInfo = [TCSGGeneralMethods infoDict:[[note userInfo] objectForKey:@"NSDevicePath"]];
    NSLog(@"pathDict: %@",pathInfo);
	if([[pathInfo objectForKey:@"Device / Media Name"] isEqualToString:@"Sony PRS-505/UC Media"])
	{
		PRS505Device = [[note userInfo] objectForKey:@"NSDevicePath"];
	}
	if([pathInfo objectForKey:@"Device Identifier"] != [pathInfo objectForKey:@"Part Of Whole"])
	{
		NSLog(@"not base");
		NSDictionary *pathInfoToo = [TCSGGeneralMethods infoDict:[pathInfo objectForKey:@"Part Of Whole"]];
		NSLog(@"too: %@",[pathInfoToo objectForKey:@"Device / Media Name"]);
		if([[pathInfoToo objectForKey:@"Device / Media Name"] isEqualToString:@"Sony PRS-505/UC:SD Media"])
		{
			PRS505Media = [[note userInfo] objectForKey:@"NSDevicePath"];
			NSLog(@"path:%@",[TCSGGeneralMethods epubPathForHTMLCode:@"FW_77238"]);
			if([[NSFileManager defaultManager] fileExistsAtPath:[TCSGGeneralMethods epubPathForHTMLCode:@"FW_77238"]])
			{
				
				[[NSFileManager defaultManager] copyPath:[TCSGGeneralMethods epubPathForHTMLCode:@"FW_77238"] toPath:[[PRS505Media stringByAppendingPathComponent:@"StoryGrabber"] stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.epub",@"FW_77238"]] handler:nil];
				NSLog(@"copying");
			}
		}
		[pathInfoToo release];

	}
	[pathInfo release];
    NSLog(@"PRS505Device: %@, Media: %@",PRS505Device, PRS505Media);
}
#pragma mark urlconnection delegates
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // this method is called when the server has determined that it
    // has enough information to create the NSURLResponse
	
    // it can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
    // receivedData is declared as a method instance elsewhere
    [data setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)datas
{
    // append the new data to the receivedData
    // receivedData is declared as a method instance elsewhere
    [data appendData:datas];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    // release the connection, and the data object
    [connection release];
    [data	release];
}
- (void)setPopUpSelection:(NSNotification *)note
{
	[popUpButton selectItemAtIndex:[[note object] intValue]];
}

-(void)setObjects:(NSNotification *)note
{
	addedObjects = [note object];
}
- (NSViewController*)viewController
{
	return myCurrentViewController;
}
@end
